from flask import Flask, render_template, request, jsonify
from PIL import Image
from message_class import agvRobot,agvRobotList
import json
import os

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'static/img/'  # 设置上传文件夹

robot_data_list = agvRobotList(filename='robots.json')
# 目标队列
goal_queue=[]
# 重设信号
resetSign=None
'''
客户端网页端
'''
# 给前端当前所有机器人的信息（json：'map','x','y'）
@app.route('/datajson')
def data_json():
    global robot_data_list
    return jsonify(json.loads(robot_data_list.get_json()))

# 前端发目标点（json：'map','x','y'）
@app.route('/post-goal', methods=['POST'])
def post_goal():
    global goal_queue
    global robot_data_list
    # 读取数据
    data = request.get_json()
    if not data:
        return 'No data provided', 400
    # 寻找'map'地图中距离goal最近的机器人
    robot=robot_data_list.find_closest_robot_with_charge_not_expired(data['map'],data['x'],data['y'])
    if robot:
        goal_queue.append([robot.id,data['x'],data['y']])
    else:
        print('no robot can go')

@app.route('/reset-robot', methods=['POST'])
def reset_robot():
    global resetSign
    # 读取数据
    data = request.get_json()
    if not data:
        return 'No data provided', 400
    resetSign=data['data']
    

'''
agv端
'''
# 接收图片，只有建图的时候用
@app.route('/get-image', methods=['POST'])
def get_image():
    if 'image' not in request.files:
        return 'No image part'
    file = request.files['image']
    if file.filename == '':
        return 'No selected file'
    if file:
        # 确保文件名是安全的
        filename = file.filename
        # 读取图片
        image = Image.open(file)
        # 添加JPEG扩展名
        filename_jpg = filename.rsplit('.', 1)[0] + '.jpg'
        # 保存图片为JPEG格式
        image.save(os.path.join(app.config['UPLOAD_FOLDER'], filename_jpg), 'JPEG')
        return 'Image successfully saved as JPEG'
    else:
        return 'Invalid file type'

# 机器人向上位机发
@app.route('/post-position', methods=['POST'])
def post_position():
    global robot_data_list
    global goal_queue
    global resetSign
    # 读取数据
    data = request.get_json()
    if not data:
        return 'No data provided', 400
    # 更新数据
    robot_data=agvRobot(data['id'],data['x'],data['y'],data['map'],data['timeout'],data['charge'])
    robot_data_list.update_robot(robot_data)
    # 返回一个目标位置
    if len(goal_queue)>0:
        goal_data=goal_queue.pop(0)
    else:
        goal_data=None
    if goal_data and int(data['id'])==int(goal_data[0]):
        target_position = {'x': goal_data[1], 'y': goal_data[2],'charge':True}
    else:
        target_position = {'x': 0, 'y': 0,'charge':False}
    
    # 手动解除
    if data['id']==resetSign and data['charge']:
        target_position = {'reset':1}
        resetSign = None
    return jsonify(target_position)


@app.route('/server/<string:map>')
def display_server(map):
    return render_template('server.html',map=map)

@app.route('/client/<string:map>/<int:position_x>/<int:position_y>')
def display_item(map,position_x,position_y):
    return render_template('client.html', map=map, position_x=position_x,position_y=position_y)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=3508)
